/*************************************************************************
 * File Name:    Palindrome_Partitioning.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: Sun 27 Oct 2013 10:32:04 PM CST
 * 
 * Description:  
 |-----------------------------------------------------------------------
 | Problem: Palindrome Partitioning
 |
 | Given a string s, partition s such that every substring of the partition
 | is a palindrome.
 |
 | Return all possible palindrome partitioning of s.
 |
 | For example, given s = "aab",
 |
 | Return
 | [
 |   ["aa","b"],
 |   ["a","a","b"]
 | ]
 |-----------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <iomanip>

using namespace std;

class Solution {
private:
    vector<vector<bool> > dp;
    vector<vector<string> > ans;

public:
    vector<vector<string> > partition(string s)
    {
        dp.clear();
        dp = vector<vector<bool> >(s.size(), vector<bool>(s.size() + 1, false));
        
        for (size_t i = 0; i < s.size(); ++i) {
            dp[i][0] = dp[i][1] = true;
        }
        for (size_t len = 2; len <= s.size(); ++len) {
            for (size_t i = 0; i + len <= s.size(); ++i) {
                if (s[i] == s[i + len - 1] && dp[i + 1][len - 2]) {
                    dp[i][len] = true;
                }
            }
        }
        ans.clear();
        vector<string> part;
        dfs(0, s, part);
        
        return ans;
    }
    
    void dfs(size_t p, const string &s, vector<string> &part)
    {
        if (p >= s.size()) {
            ans.push_back(part);
            return;
        }
        for (size_t i = p; i < s.size(); ++i) {
            if (!dp[p][i - p + 1]) continue;
            part.push_back(s.substr(p, i - p + 1));
            dfs(i + 1, s, part);
            part.pop_back();
        }
    }
};
